/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.SLC;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import merlion.crm.slcm.entity.Customer;
import merlion.crm.slcm.entity.MemberDiscountGroup;
import merlion.crm.slcm.session.SLCSessionBeanLocal;

/**
 *
 * @author Kenn
 */
@ManagedBean(name = "mdgManagerBean")
@ViewScoped
public class MemberDiscountManagerBean {

    @EJB
    private SLCSessionBeanLocal slcSessionBean;
    private MemberDiscountGroup mdg;
    private Customer customer;
    private Collection<MemberDiscountGroup> mdgs;
    private Collection<Customer> customers;
    private Boolean create;
    public static final String memberDiscountGroup = "mdg";
    public static final String booleanCreate = "create";
    //--------------------------------------------------------------------------
    //                              Constructor
    //--------------------------------------------------------------------------
    public MemberDiscountManagerBean() {
        System.out.print("#########################MmberDiscountMamagerBean initiated in MemberDiscount");
        resetSession();
    }

    private void resetSession() {
        mdg = new MemberDiscountGroup();
        customer = new Customer();
        mdgs = new ArrayList<MemberDiscountGroup>();
        customers = new ArrayList<Customer>();
        create = true;
    }

    //--------------------------------------------------------------------------
    //                           Getter and Setter
    //--------------------------------------------------------------------------
    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public Collection<Customer> getCustomers() {
        return customers;
    }

    public void setCustomers(Collection<Customer> customers) {
        this.customers = customers;
    }

    public MemberDiscountGroup getMdg() {
        System.out.print("################# enter getMdg() at MemberDiscount bean line 71");
        MemberDiscountGroup value = (MemberDiscountGroup) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(memberDiscountGroup);
        System.out.print("#################  at MemberDiscount bean line 73" + value);
        if (value != null) {
            mdg = value;
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(memberDiscountGroup);
        }

        return mdg;
    }

    public void setMdg(MemberDiscountGroup mdg) {
        this.mdg = mdg;
    }

    public Collection<MemberDiscountGroup> getMdgs() {
        return mdgs;
    }

    public void setMdgs(Collection<MemberDiscountGroup> mdgs) {
        this.mdgs = mdgs;
    }

    public Boolean getCreate() {
        Boolean value = (Boolean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(booleanCreate);
        if (value != null) {
            create = value;
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(booleanCreate);
        }
        return create;
    }

    public void setCreate(Boolean create) {
        this.create = create;
    }

    //--------------------------------------------------------------------------
    //                      Manager Bean Methods
    //--------------------------------------------------------------------------
    public String viewMemberDiscountGroup() {
        //System.out.println("MemberDiscountManagerBean viewMemberDiscountGroup");
        resetSession();
        return "viewAllMemberDiscountGroup?faces-redirect=true";
    }

    public Collection<MemberDiscountGroup> viewAllMemberDiscount() {
        setMdgs(slcSessionBean.getAllMemberDiscountGroup());
        return mdgs;
    }

    public String createMemberDiscountGroup(Long i) {

        if (i == 0) {
            //System.out.println("Create Member discount group line 112");
            resetSession();
            return "manageMemberDiscountGroup";
        } else {
            //Validate
            //System.out.println("Create boolean at line 113: " + create);
            if (!validate(mdg)) {
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(memberDiscountGroup,  mdg);
             FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(booleanCreate,  create);    
                return "manageMemberDiscountGroup";
            }
            //System.out.println("Create boolean at line 117: " + create);
            if(getCreate()){
                //System.out.println("Create boolean at line 119: " + create);
                mdg = slcSessionBean.createMemberDiscountGroup(mdg);
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Member Discount Group", "successfully created."));
            } else {
                //System.out.println("Create boolean at line 123: " + create);
                mdg = slcSessionBean.updateMemberDiscountGroup(mdg);
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Member Discount Group", "successfully updated."));
            }
            
            // Reset Manager Bean odg and product object after creating
            //System.out.println("MemberDiscountManagerBean line 133 reset");
            resetSession();       
            return "manageMemberDiscountGroup";
        }
    }

    public String updateMemberDiscountGroup(Long id) {
        try {
            setMdg(slcSessionBean.getMemberDiscountGroupById(id));
            setCreate(false);
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(memberDiscountGroup,  mdg);
             FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(booleanCreate,  create);
            //System.out.println("Create boolean at line 143: " + create);
            return "manageMemberDiscountGroup";

        } catch (Exception e) {
            return "error";
        }
    }
    
    // hold value for deletion
    public void beforeDelete (Long id) {
        mdg = slcSessionBean.getMemberDiscountGroupById(id);
       
        
    }
    
    public String deleteMemberDiscountGroup() {
        System.out.print("############################"+mdg.getId());
        try{
            String msg = slcSessionBean.deleteMemberDiscountGroup(mdg.getId());
            if(msg.equals("customerExist")) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "The seleted group has been assigned to some customers", "cannot be deleted."));
            }
            else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Member Discount Group", "successfully deleted."));
            }
        }
        catch (Exception e) {
            System.out.print(e.getMessage());
            return "error";
        }
        return "manageMemberDiscountGroup";
    }
    
    //-------------------------------------------------------------------------
    //              OrderDiscountManager Bean Customer Validator
    //-------------------------------------------------------------------------

    private boolean isAlphabetic(String str) {
        if (str.matches("[a-zA-Z\\s]*")) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isAlphanumeric(String str) {

        if (str.matches("[a-zA-z0-9\\s]*")) {
            return true;
        } else {
            return false;
        }

    }

    private boolean isNumeric(String str) {
        if (str.matches("[0-9]*")) {
            return true;
        } else {
            return false;
        }

    }

    private boolean isNotEmpty(String str) {
        if (str == null) {
            return false;
        }
        if (str.equals("")) {
            return false;
        }
        return true;
    }

    private boolean validate(MemberDiscountGroup mdg) {

        boolean valid = true;
        // Member Discount Group Name: Required, Alphanumeric
        if (!isNotEmpty(mdg.getGroup())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Member Discount Group Name", "cannot be empty."));
            valid = false;
        }
        if (!isAlphanumeric(mdg.getGroup())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Member Discount Group Name", "can only contain alphanumeric characters."));
            valid = false;
        }
        
        //Accumulated spending required for whole sales
        if(mdg.getAccSpendingForWs()== null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Accumulated spending (Whole Sales)", "cannot be empty."));
            valid = false;
        } else if(mdg.getAccSpendingForWs()<=0) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Accumulated spending (Whole Sales)", "cannot be <= 0."));
                valid = false;
        }
        //Accumulated spending required for direct sales
        if(mdg.getAccSpendingForDs()== null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Accumulated spending (Direct Sales)", "cannot be empty."));
            valid = false;
        } else if(mdg.getAccSpendingForDs()<=0) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Accumulated spending (Direct Sales)", "cannot be <= 0."));
                valid = false;
        }

        //Member discount: Required, not 0
        if (mdg.getMemberDiscount() == null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Member Discount", "cannot be empty."));
            valid = false;
        } else {
            if (mdg.getMemberDiscount() <= 0) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Member Discount", "cannot be <= 0."));
                valid = false;
            }
            if (mdg.getMemberDiscount() >= 1) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Member Discount", "cannot be >= 1."));
                valid = false;
            }
        }
        
        
        
        // when "create" is true, need to check whether the mdg already exists.
        // when "create" is false, means the user is updating some existing mdg, no need to check in this case.
        if (getCreate() && exist(mdg)) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Member Discount Group", "already exists."));
            valid = false;
        }

        return valid;
    }
    
    private boolean exist(MemberDiscountGroup mdg) {
        boolean exist = false;
        List<MemberDiscountGroup> temp = new ArrayList<MemberDiscountGroup>();
        temp = slcSessionBean.getAllMemberDiscountGroup();
        for(int i = 0;i<temp.size();i++){
            //System.out.print("#########################"+temp.get(i).getGroup());
            //System.out.print("#########################"+mdg.getGroup());
            //System.out.print("#########################"+temp.get(i).getMemberDiscount());
            //System.out.print("#########################"+mdg.getMemberDiscount());
            //System.out.print("#########################"+temp.get(i).getGroup().equalsIgnoreCase(mdg.getGroup()));
            //System.out.print("#########################"+ (temp.get(i).getMemberDiscount().compareTo(mdg.getMemberDiscount())==0));
            if(temp.get(i).getGroup().equalsIgnoreCase(mdg.getGroup())) {
                exist = true;
                return exist;
            }
        }
        return exist;


    }
}